package com.qmctl.util;

import java.io.FileInputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class HttpConnectUtils {
	public static void main(String[] args){
        String Url = "http://qimenapi.tbsandbox.com/top/router/qimen/service?"  //线上地址     日常地址："http://qimenapi.tbsandbox.com/router/qimen/service?"
        		+ "method=taobao.qimen.entryorder.confirm"
        		+ "&timestamp=2016-05-09%2017:34:45"   
        		+ "&format=xml"
        		+ "&app_key=1023355349"
        		+ "&v=2.0"
        		+ "&sign_method=md5"
        		+ "&customerId=c1462687545544";
        
        String body = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><request><orderLines/><entryOrder><confirmType>1</confirmType><entryOrderCode>e0004</entryOrderCode><entryOrderId>16207</entryOrderId><entryOrderType>SCRK</entryOrderType><operateTime>2016-05-09 14:01:12</operateTime><outBizCode></outBizCode><ownerCode>MFSJ</ownerCode><remark></remark><status>ACCEPT</status><totalOrderLines>0</totalOrderLines><warehouseCode>511538032</warehouseCode></entryOrder></request>";
        String secretKey = "sandboxca21e78096cfd80d15dba32ef";
        try{
        	QimenSign signer = new QimenSign();
        	String md5 = signer.sign(Url, body, secretKey);        	
        	System.out.println(md5);        	
        	
        	String Url1 = Url + "&sign=" + md5;
        	System.out.println(Url1);
        	
            String response = HttpConnectUtils.send(Url1, body);       //注意：签名的body和http请求的body必须完全一致，包括空格、换行等
            System.out.println(response);
            
        }catch (Exception e){
            e.printStackTrace();
        }
    }
	public static String send(String url, String body) throws Exception {
		CloseableHttpClient client = HttpClientBuilder.create().build();
		try{
          HttpPost post = new HttpPost(url);
          HttpEntity entity = new StringEntity(body, "utf-8");
          post.setEntity(entity);
          HttpResponse response = client.execute(post);
          if (response.getStatusLine().getStatusCode() == 200) {
            String resEntityStr = EntityUtils.toString(response.getEntity(),"UTF-8");
            System.out.println("***url:\t"+url+"\nbody:"+body+"\n报文返回:\t"+resEntityStr);
            return replaceFilter(resEntityStr);
            //return new String(resEntityStr.getBytes("GBK"), "UTF-8");//如果出现乱码，需要手动转码
          } else {
            //TODO
          }
		}finally{
          client.close();
		}
        return null;
    }
	public static String send(String url) throws Exception {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        try{
          HttpPost post = new HttpPost(url);
        //post.setEntity(entity);
        
          CloseableHttpResponse response = client.execute(post);
          if (response.getStatusLine().getStatusCode() == 200) {
            String resEntityStr = EntityUtils.toString(response.getEntity());
            return resEntityStr;
            //return new String(resEntityStr.getBytes("GBK"), "UTF-8");//如果出现乱码，需要手动转码
          } else {
            //TODO
          }
        }
        finally{
        	client.close();
        }
        return null;
    }
	public static String sendToQimen(Map<String,String> params,String body,String baseUrl,String secretKey) throws Exception {
		/*
		 * http://qimen.api.taobao.com/router/qimen/service?method=[qimen_API] &timestamp=[2015-02-01 00:00:00]&format=xml&app_key=[wms_appkey]&v=1.0&sign=[xxxxxxxxxxxxxxxxxxxxxx]&sign_method=md5&customerId=[QIMENUSR1]
		 * */        
        StringBuilder sb = new StringBuilder(baseUrl); // 前面加上secretKey
        for ( String key : params.keySet() ) {
          String value = params.get(key);
          sb.append( String.format("%s=%s&",key,value) );
        }
        QimenSign sign = new QimenSign();
        String signature = sign.sign(params, body, secretKey);
        sb.append( String.format("sign=%s", signature) );
		
        String url=URLEncoder.encode(sb.toString());
        return send(url,body);
	}
	public static String sendToQimen(String method,String body,String baseUrl,String appkey,String cstmid,String v,String secretKey) throws Exception {
		/*
		 * http://qimen.api.taobao.com/router/qimen/service?method=[qimen_API] 
		 * &timestamp=[2015-02-01 00:00:00]&format=xml
		 * &app_key=[wms_appkey]
		 * &v=1.0
		 * &sign=[xxxxxxxxxxxxxxxxxxxxxx]
		 * &sign_method=md5
		 * &customerId=[QIMENUSR1]
		 * */   
		Map<String,String> params = new HashMap<String,String>();
		params.put("method", method);
		params.put("timestamp", SysTools.getTimeStampManuanl());
		params.put("app_key", appkey);
		params.put("customerId",cstmid);
		params.put("sign_method","md5");
		params.put("format","xml");
		params.put("v",v);
        QimenSign sign = new QimenSign();
        String signature = sign.sign(params, body, secretKey);
        System.out.println("baseUrl:\t"+baseUrl);
        StringBuilder sb = new StringBuilder(baseUrl); // 前面加上secretKey
        for ( String key : params.keySet() ) {
          String value = params.get(key);
          if(key.equals("timestamp"))
            sb.append( String.format( "%s=%s&",key, value.replace(" ", "%20")));
          else
            sb.append( String.format( "%s=%s&",key,value) );
        	  
        }

        sb.append( String.format("sign=%s", signature) );
		
        String url=sb.toString();
        return send(url,body);
	}
	
	public static String sendToqm(String method, String sendMsgToQm,
			Properties properties,String customerid) throws Exception {
		return HttpConnectUtils.sendToQimen(method, sendMsgToQm,
				SysTools.getProperty("qmUrl", properties),
				SysTools.getProperty("appkey", properties),
				customerid==null||"".equals(customerid)?SysTools.getProperty("customId", properties):customerid,
				SysTools.getProperty("version", properties),
				SysTools.getProperty("wmsSecretKey", properties));
	}
	
	public static boolean filter(String str){

	    String[] stra=new String[]{"CGI","cgi","URL","url","<SCRIPT>","<script>","</SCRIPT>","</script>","http:","HTTP:","+ADW-"};
	    for (int i=0 ; i < stra.length ; i++ ){
	        if (str.indexOf(stra[i])>=0){
	            return true;
	        }
	    }
	    return false;
	}

	public static String replaceFilter(String str){
//	    String xss = "|CGI|cgi|URL|url|<SCRIPT>|<script>|</SCRIPT>|</script>|http:|HTTP:|+ADW-|";

	    String[] stra=new String[]{"CGI","cgi","URL","url","<SCRIPT>","<script>","</SCRIPT>","</script>","http:","HTTP:","+ADW-"};
	    for (int i=0 ; i < stra.length ; i++ ){
	        if (str.indexOf(stra[i])>=0){
	          str = str.replaceAll(stra[i], "");
	        }
	    }
	    return str;
	}
}
